package com.lqm.web.controller.admin;

import com.lqm.entity.admin.AdminUser;
import com.lqm.service.admin.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: CrowdFunding
 * @description
 * @author: lqm
 * @create: 2018-12-05 17:52
 */
@RestController
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    AdminUserService adminUserService;

    /**
     * 后台用户登录
     *
     * @param adminUser
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public Map<String, Object> login(AdminUser adminUser, HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        String md5Password = DigestUtils.md5DigestAsHex(adminUser.getPassword().getBytes());
        AdminUser user = adminUserService.findAllByUsernameAndPassword(adminUser.getUsername(), md5Password);
        System.out.println(user);
        //登录成功
        if (user != null) {
            request.getSession().setAttribute("admin_user", user);
            map.put("code", 0);
            map.put("msg", "登录成功");
        } else {
            map.put("code", 101);
            map.put("msg", "登录失败,用户名与密码不匹配");
        }
        return map;
    }


    /**
     * 获取登录的后台用户信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/getAdminUser")
    public Map<String, Object> getAdminUser(HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        AdminUser user = (AdminUser) request.getSession().getAttribute("admin_user");
        if (user != null) {
            map.put("code", 0);
            map.put("msg", "当前登录信息获取成功");
            map.put("data", user);
            System.out.println("AdminUserController->getAdminUser:" + map);
        } else {
//            map.put("code", 10001);
            map.put("code", 0);
            map.put("msg", "当前处于未登录状态");
            map.put("data", null);
        }
        return map;
    }


    /**
     * 退出登录
     *
     * @param request
     * @return 是否成功信息
     */
    @RequestMapping("/logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        try {
            request.getSession().setAttribute("admin_user", null);
            map.put("code", 0);
            map.put("msg", "退出成功");
        } catch (Exception e) {
            map.put("code", 101);
            map.put("msg", "退出失败，请重试");
        }
        System.out.println(map);
        return map;
    }
}
